package com.ns.dcjh.utils.upyun

import android.util.Log
import java.text.SimpleDateFormat
import java.util.*

/**
 * 时间工具类
 */
object TimeUtils {


    const val FORMAT_DAY = "yyyy-MM-dd"
    const val FORMAT_SECOND = "yyyy-MM-dd HH:mm:ss"
    const val FORMAT_YEAR = "yyyy"

    const val FORMAT_MONTH_DAY = "MM.dd"

    const val TEN_YEARS_DAYS = 10 * 365 //十年天数
    const val dayMillis = 86400000

    const val FORMAT_TIME = "HH:mm:ss"

    /**
     * 获取当前时间
     */
    fun getCurrTime(format: String = FORMAT_SECOND): String {
        val simpleDateFormat = SimpleDateFormat(format)// HH:mm:ss
        val date = Date(System.currentTimeMillis())//获取当前时间
        val currTime = simpleDateFormat.format(date)
        return currTime
    }


    /**
     * 获取时间戳
     */
    fun getTimestamp() = System.currentTimeMillis()


    fun isSameDay(time1: Long?, time2: Long?): Boolean {
        try {
            if (time1 != null && time2 != null) {

                val nowCal = Calendar.getInstance()
                val dataCal = Calendar.getInstance()

                val df1 = SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
                val df2 = SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
                val data1 = df1.format(time1)
                val data2 = df2.format(time2)

                val now: java.util.Date = df1.parse(data1)
                val date: java.util.Date = df2.parse(data2)

                nowCal.time = now
                dataCal.time = date

                return nowCal.get(Calendar.ERA) == dataCal.get(Calendar.ERA)
                        && nowCal.get(Calendar.YEAR) == dataCal.get(Calendar.YEAR)
                        && nowCal.get(Calendar.DAY_OF_YEAR) == dataCal.get(Calendar.DAY_OF_YEAR)
            } else {
                return false
            }
        } catch (e: java.lang.Exception) {
            Log.e("TAG","解析错误")
            return false
        }
    }

    /**
     * 计算时间间隔
     */
    fun getTimeInterval(startDate: String, endDate: String): Long {

        var sdf = SimpleDateFormat("yyyy-MM-dd")


        var theStartTime = stringToDate(startDate)
        var theEndTime = stringToDate(endDate)


        var startDate = sdf.parse(sdf.format(theStartTime))
        var endDate = sdf.parse(sdf.format(theEndTime))

        var calendar = Calendar.getInstance()
        calendar.setTime(startDate)

        var time1 = calendar.getTimeInMillis()


        calendar.setTime(endDate);
        var time2 = calendar.getTimeInMillis()


        var betweenDays = (time2 - time1) / (1000 * 3600 * 24)

        return betweenDays
    }


    @Throws(Exception::class)
    fun stringToDate(strDate: String): Date {
        val df = SimpleDateFormat("yyyy-MM-dd")
        val date = df.parse(strDate)
        val time = date.time
        Log.e("TAG","时间戳---->$time")
        return Date(time)
    }

//
//    fun secondToDay(second: String): String {
//        if (StringUtils.isEmpty(second)) return ""
//        var result = ""
//        try {
//            val se = SimpleDateFormat(FORMAT_SECOND)
//            val day = SimpleDateFormat(FORMAT_DAY)
//
//            val date = se.parse(second)
//
//            result = day.format(date)
//        } catch (e: java.lang.Exception) {
//            LogUtils.e("解析出问题")
//        }
//        return result
//    }


    /**
     * long转换为String
     */
    fun longToStringData(fromTime: Long, format: String = "yyyy-MM-dd"): String {
        val date = Date(fromTime)
        var returnTime = ""

        if (fromTime != 0L) {
            try {
                val sdf = SimpleDateFormat(format)
                returnTime = sdf.format(date)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return returnTime
    }


    /********************** 以日为最小单位的时间 *************************/

    fun getCurrYear(): String {
        val sf = SimpleDateFormat(FORMAT_YEAR)
        val date = Date(System.currentTimeMillis())
        return sf.format(date)
    }

    /**
     * 获取当前日期
     */
    fun getCurrDay(): String {
        val sf = SimpleDateFormat(FORMAT_DAY)
        val date = Date(System.currentTimeMillis())
        return sf.format(date)
    }

    /**
     * 获取当前日期(自定义)
     */
    fun getCurrDayFormat(format: String): String {
        val sf = SimpleDateFormat(format)
        val date = Date(System.currentTimeMillis())
        return sf.format(date)
    }

    /**
     * 计算两个日期间隔天数
     */
    fun daysBetween(startDay: String, endDay: String): Int {
        var between = 0L
        try {
            val sf = SimpleDateFormat(FORMAT_DAY)
            val cal: Calendar = Calendar.getInstance()

            cal.time = sf.parse(startDay)
            val time1: Long = cal.timeInMillis

            cal.time = sf.parse(endDay)
            val time2: Long = cal.timeInMillis

            between = (time2 - time1) / (1000 * 3600 * 24)

        } catch (e: Exception) {
            Log.e("TAG","时间解析错误")
        }
        return between.toInt()
    }

    /**
     * 获取某个日期距离当前时间的天数
     */
    fun getDayToNow(day: String): Int = daysBetween(day, getCurrDay())


    /********************** 日期格式转化 *************************/
    fun secondToDay(secondOfDate: String?): String {
        if (secondOfDate == null) return ""
        val sf = SimpleDateFormat(FORMAT_DAY)
        var result: String = ""
        try {
            val time = sf.parse(secondOfDate)
            result = sf.format(time)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return result
    }

    /********************** 年月日的判断 *************************/


    fun isScrq(year: String, month: String, day: String): Boolean {
        val inputDay = "$year-$month-$day"
        val days = getDayToNow(inputDay)//输入日期距今的天数
        return days in -TEN_YEARS_DAYS..TEN_YEARS_DAYS
    }


    /**
     * 判断是否是生产日期年份
     * 往前十年，往后十年
     */
    fun isScrqYear(year: String): Boolean {
        val years = getCurrYear().toInt() - year.toInt()
        return !(years > 10 || years < -10)
    }


    /**
     * 判断是否是月份
     */
    fun isMonth(month: String) = month.toInt() in 1..12


    /**
     * 判断是否是日数
     */
    fun isDay(year: String, month: String, day: String) =
        day.toInt() in 1..getMaxDayOfMonth(year, month)


    /**
     * 获取某年某月的days
     */
    fun getMaxDayOfMonth(year: String, month: String): Int {
        val month31 = intArrayOf(1, 3, 5, 7, 8, 10, 12)
        val month30 = intArrayOf(4, 6, 9, 11)
        var daymax = 30

        if (month31.contains(month.toInt())) daymax = 31
        else if (month30.contains(month.toInt())) daymax = 30
        else {
            //年份能够整除4且不整除100，是闰年
            if (year!!.toInt() % 4 == 0 && year.toInt() % 100 != 0) {
                daymax = 29
            } else if (year.toInt() % 400 == 0) {//年份整除400是闰年
                daymax = 29
            } else daymax = 28
        }

        return daymax
    }

    fun getDateForNeed(format: String, diff: Int): String {
        val todayTimePoint = getTimestamp()
        val date = Date(todayTimePoint)
        val calendar = Calendar.getInstance()
        calendar.time = date
        calendar.add(Calendar.DAY_OF_MONTH, diff)
        val needDate = calendar.time
        val formatter = SimpleDateFormat(format)
        return formatter.format(needDate)
    }

    fun getDateStrNeed(dateStr:String):String{
        val sdf = SimpleDateFormat(FORMAT_DAY)
        val date = sdf.parse(dateStr)
        val sdf1 = SimpleDateFormat(FORMAT_MONTH_DAY)
        return sdf1.format(date)
    }


    /**
     * 获取当前时间为起点的7天时间列表
     */
    fun getTodayStart7Days(): MutableList<String> {
        val timeList = mutableListOf<String>()
        for (index in 0 until 7) {
            timeList.add(getDateForNeed(FORMAT_MONTH_DAY, index))
        }
        return timeList
    }


    /**
     * 获取当前时间
     */
    fun getCurrTimeMMdd(day: Int): String {
        val simpleDateFormat = SimpleDateFormat("MM.dd", Locale.CHINA)
        val date = Date(System.currentTimeMillis() + day * dayMillis)//获取当前时间
        val currTime = simpleDateFormat.format(date)
        return currTime
    }

    /**
     * 获取周几 E周几，EEEE星期几
     */
    fun getCurrTimeE(day: Int): String {
        val simpleDateFormat = SimpleDateFormat("E", Locale.CHINA)
        val date = Date(System.currentTimeMillis() + day * dayMillis)//获取当前时间
        val currTime = simpleDateFormat.format(date)
        return currTime
    }

    /**
     * 获取N天后的时间
     */
    fun getCurrTimeYMD(day: Int): String {
        val simpleDateFormat = SimpleDateFormat(FORMAT_DAY, Locale.CHINA)
        val date = Date(System.currentTimeMillis() + day * dayMillis)//获取当前时间
        val currTime = simpleDateFormat.format(date)
        return currTime
    }

    /**
     * 获取年月日
     */
    fun getCurrTimeYM(mDate: String): String {
        return if (mDate.isEmpty()) {
            val simpleDateFormat = SimpleDateFormat("yyyy-MM", Locale.CHINA)
            val date = Date(System.currentTimeMillis())//获取当前时间
            simpleDateFormat.format(date) + "-1"
        } else {
            val simpleDateFormat = SimpleDateFormat("yyyy-MM", Locale.CHINA)
            val date = Date(System.currentTimeMillis())//获取当前时间
            simpleDateFormat.format(date) + "-1"
        }
    }

    /**
     * 获取N年后的时间
     */
    fun getMinOrMaxTime(minOrMax: Int): String {
        return when (minOrMax) {
            1 -> {
                val simpleDateFormat = SimpleDateFormat("yyyy", Locale.CHINA)
                val date = Date(System.currentTimeMillis())//获取当前时间
                val year = Integer.parseInt(simpleDateFormat.format(date)) + 5
                val mdhm = getCurrTime("12-31")
                "$year-$mdhm"
            }
            else -> {
                getCurrTime("yyyy-1-1")
            }
        }
    }

    /**
     * 获取运动tab中String
     */
    fun getSportDay(day: Int): String {
        return when (day) {
            0 -> {
                "今天"
            }
            1 -> {
                "明天"
            }
            2 -> {
                "后天"
            }
            else -> {
                getCurrTimeE(day)
            }
        }
    }


    /**
     * 根据时间判断先后
     */
    fun judgeTime2IsAfterOrSame(time1: String, time2: String): Boolean {
        val sdf = SimpleDateFormat(FORMAT_TIME, Locale.CHINA)
        val date1 = sdf.parse(time1)
        val date2 = sdf.parse(time2)
        if (date1 == date2)
            return true

        return date1.before(date2)
    }

    /**
     * 根据时间判断先后
     */
    fun judgeTime2IsAfter(time1: String, time2: String): Boolean {
        val sdf = SimpleDateFormat(FORMAT_TIME, Locale.CHINA)
        val date1 = sdf.parse(time1)
        val date2 = sdf.parse(time2)
        return date1.before(date2)
    }

    /**
     * 根据周几获取最近的日期
     * @param week 星期数  周一代表1
     * @return 最近的日期 yyyy-MM-dd
     */
    fun getRecentDateFormWeek(week: Int): String {
        var targetWeek = -1
        if (week < 7) {
            targetWeek = week + 1
        } else if (week == 7) {
            targetWeek = 1
        }
        val c = Calendar.getInstance()
        val currWeek = c.get(Calendar.DAY_OF_WEEK) //获取当前时间的星期
        if (targetWeek == currWeek) {
            return date2String(c.time, FORMAT_MONTH_DAY)
        }
        while (targetWeek != c.get(Calendar.DAY_OF_WEEK)) {
            c.add(Calendar.DAY_OF_MONTH, 1)
        }

        return date2String(c.time, FORMAT_MONTH_DAY)
    }

    fun getMillisToHour(millis: Long): String {

        val spaceTime = (getTimestamp() - millis) / 1000

        return when {
            spaceTime < 60 -> {
                "不足1分钟"
            }
            spaceTime < 3600 -> {
                "${spaceTime / 60}分钟"
            }
            else -> {
                "${spaceTime / 3600}小时${spaceTime % 3600 / 60}分钟"
            }
        }
    }

    /**
     * Date类型转为String
     */
    fun date2String(date: Date, format: String = FORMAT_DAY): String {
        val sdf = SimpleDateFormat(format)
        return sdf.format(date)
    }

    fun strTime2OtherTimeStr(dateStr: String, format: String = FORMAT_DAY): String {
        val df = SimpleDateFormat(FORMAT_DAY)
        val date = df.parse(dateStr)
        return date2String(date, format)
    }

}